<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">

        <a-row>
          <a-col :span="8">
            <a-form-model-item label="包材采购订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowType">
              <j-dict-select-tag
                type="list"
                v-model="model.flowType"
                dictCode="package_order_flow_type"
                placeholder="请选择审批流程"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="付款方式"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="payment"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.payment"
                dictCode="payment_method"
                placeholder="请选择付款方式"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <!--<a-col :span="8">
            <a-form-model-item
              label="付款时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="paymentTime"
            >
              <a-input v-model="model.paymentTime" placeholder="请输入付款时间"></a-input>
            </a-form-model-item>
          </a-col>-->
          <a-col :span="8">
            <a-form-model-item
              label="付款时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="paymentTime">

              <j-date-general placeholder="请选择付款时间" v-model="model.paymentTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="运输方式"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="transport"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.transport"
                dictCode="transportation_method"
                placeholder="请选择运输方式"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <!--<a-form-model-item
              label="到货日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalDate"
            >
              <a-input v-model="model.arrivalDate" placeholder="请输入到货日期"></a-input>
            </a-form-model-item>-->
            <a-form-model-item
              label="到货日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalDate"
            >
              <j-date
                placeholder="请选择日期"
                v-model="model.arrivalDate"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item label="供货单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierCompany">
              <j-popup
                v-model="model.supplierCompany"
                field="supplierCompany"
                org-fields="id,supplier_name,address,appointed_agent_name,phone,tax_code,bank,bank_code,zip_code"
                dest-fields="supplierId,supplierCompany,supplierAddress,supplierBy,supplierPhone,supplierTax,supplierBank,supplierAccount,supplierMail"
                code="supplier_main_info"
                :multi="false"
                @input="popupCallback"
              />
              <a-input v-model="model.supplierId" placeholder="供货商ID" type="hidden"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="发件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierBy"
            >
              <a-input v-model="model.supplierBy" placeholder="请输入发件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="发件人电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierPhone"
            >
              <a-input v-model="model.supplierPhone" placeholder="请输入发件人电话"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="收件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseBy"
            >
              <a-input v-model="model.purchaseBy" placeholder="请输入收件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="收件人电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchasePhone"
            >
              <a-input v-model="model.purchasePhone" placeholder="收件人电话"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="收货地址"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalPlace"
            >
              <a-input v-model="model.arrivalPlace" placeholder="请输入收货地址"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="备注"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="otherRem"
            >
              <a-input v-model="model.otherRem" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row style="margin-top: 20px;">
        </a-row>
        <!-- <a-divider style="border-color: #999" dashed /> -->

        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="供方信息">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="供货单位"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierCompany"
                  >
                    <a-input v-model="model.supplierCompany"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="地址"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierAddress"
                  >
                    <a-input v-model="model.supplierAddress"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="委托代理人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierBy"
                  >
                    <a-input v-model="model.supplierBy"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="电话"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierPhone"
                  >
                    <a-input v-model="model.supplierPhone"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="税号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierTax"
                  >
                    <a-input v-model="model.supplierTax"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="开户行"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierBank"
                  >
                    <a-input v-model="model.supplierBank"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="账号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierAccount"
                  >
                    <a-input v-model="model.supplierAccount"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="邮编"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierMail"
                  >
                    <a-input v-model="model.supplierMail"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>

          <a-col :span="12">
            <a-card title="需方信息">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="需方单位"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseCompany"
                  >
                    <a-input v-model="model.purchaseCompany"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="地址"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseAddress"
                  >
                    <a-input v-model="model.purchaseAddress"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="委托代理人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseBy"
                  >
                    <a-input v-model="model.purchaseBy"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="传真电话"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchasePhone"
                  >
                    <a-input v-model="model.purchasePhone"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="税号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseTax"
                  >
                    <a-input v-model="model.purchaseTax"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="开户银行"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseBank"
                  >
                    <a-input v-model="model.purchaseBank"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="账号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseAccount"
                  >
                    <a-input v-model="model.purchaseAccount"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="邮编"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseMail"
                  >
                    <a-input v-model="model.purchaseMail"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
        </a-row>

      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="包材采购订单明细" :key="refKeys[0]" :forceRender="true">
        <a-row justify="start">
          <!-- 新增 -->
          <a-col :span="12">
            <a-space>
              <!--<a-button
                type="primary"
                icon="PlusCircleOutlined"
                size="default"
                @click="addPlan"
                v-show="!formDisabled"
              >追加</a-button>-->
              <!-- <a-button
                type="primary"
                icon="PlusCircleOutlined"
                size="default"
                @click="addTemporary"
                v-show="!formDisabled || model.procurementType == 0"
              >
                新增
              </a-button>-->
            </a-space>
          </a-col>
          <a-col :span="12"></a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
              <j-vxe-table-procurement
                keep-source
                ref="table"
                :ref="refKeys[0]"
                :loading="bussPackageProcurementDetailTable.loading"
                :columns="bussPackageProcurementDetailTable.columns"
                :dataSource="bussPackageProcurementDetailTable.dataSource"
                :maxHeight="300"
                :disabled="formDisabled"
                :rowNumber="false"
                :rowSelection="false"
                class="j-table-force-nowrap1"
                :clickSelectRow="true"
                rowSelectionType="radio"
                :scroll-x="{ enabled: true, gt: 0 }"
                @edit-closed="editClosedEvent"
              >
              <template v-slot:action="props">
                <a @click="handlePreviewFile(props)">查看版样</a>
                <divider type="vertical" />
                <a-popconfirm
                  v-show="!formDisabled"
                  title="确定删除吗？"
                  @confirm="handleDelDetail(props)"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
              <template #lossRate="props">
                  <a-form-model-item>
                    <a-input v-model="props.row.lossRate" placeholder="请输入配比(%)" @input="onChange(props)"/>
                  </a-form-model-item >
              </template>
            </j-vxe-table-procurement>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
// import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import { getAction, httpAction, postAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { validateDuplicateValue } from '@/utils/util'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
// import ErpSupplier from './ErpSupplierList.vue'
import store from '@/store'
// import PlanModal from './BussMaterialProcurementPlanList'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import moment from 'dayjs'
import ErpGoodsSupplier from '@/components/base/ErpGoodsSupplier'
import GoodsSupplier from '@/components/base/GoodsSupplier'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import TslSupplier from '@comp/tsl/TslSupplier.vue'
import { parseTime } from '@/utils/index.js'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
import TslSelectUserSingle from '@/components/tsl/TslSelectUserSingle.vue'
import Decimal from 'decimal.js'
import { FilePreview } from '@/utils/tslCommon'

export default {
  name: 'BussPackageProcurementOrderForm',
  mixins: [JVxeTableModelMixin],
  components: {
    // ErpGoodsListModel,
    // PlanModal,
    // ErpSupplier,
    JSelectDepart,
    ErpGoodsSupplier,
    GoodsSupplier,
    TslSupplier,
    TslSelectUserSingle,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      dict: {
        unit: [{ label: '个', value: '1' }],
      },
      priceTypeOption: [
        {
          value: '到库价格',
          label: '到库价格',
        },
        {
          value: '出厂价格',
          label: '出厂价格',
        },
        {
          value: '到港价格',
          label: '到港价格',
        },
      ],
      model: {
        flowType: '1',

        code: '',
        purchaseCompany: '特丝丽化工有限公司',
        purchaseBy: '张业民',
        purchasePhone: '0535-8913021',
        purchaseAddress: '山东省龙口市北马镇北马南路',
        purchaseTax: '91370681613415110K',
        purchaseBank: '中国银行龙口开发区支行',
        purchaseAccount: '226003071547',
        purchaseMail: '265702',
        packageOrderManageDetailList: [],
        otherRem: '',

        // 新增供方信息字段
        supplierCompany: '',
        supplierAddress: '',
        supplierBy: '',
        supplierPhone: '',
        supplierTax: '',
        supplierBank: '',
        supplierAccount: '',
        supplierMail: '',
        supplierId: '',
      },
      supplier: {},
      supplyShow: true,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        /*code: [{ required: true, message: '请输入单据编号!' }],
        purchaseBy: [{ required: true, message: '请填写发件人' }],
        supplierBy: [{ required: true, message: '请填写收件人' }],
        transport: [{ required: true, message: '请选择运输方式' }],
        arrivalPlace: [{ required: true, message: '请填写收货地址' }],
        payment: [{ required: true, message: '请选择付款方式' }],
        paymentTime: [{ required: true, message: '请填写付款时间' }],
        arrivalDate: [{ required: true, message: '请填写到货日期' }],*/
        flowType: [{ required: true, message: '请选择审批流程' }],
      },
      refKeys: ['bussPackageMaterialProcurementDetail'],
      tableKeys: ['bussPackageMaterialProcurementDetail'],
      activeKey: 'bussPackageMaterialProcurementDetail',
      // 原料采购订单明细
      bussPackageProcurementDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            key: 'seq',
            type: JVXETypes.normal,
            width: 80
          },
          {
            title: '订单ID',
            key: 'orderId',
            type: JVXETypes.hidden,
          },
          {
            title: '订单编号',
            key: 'schedulingNumber',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '包材到位',
            key: 'arrived',
            type: JVXETypes.normal,
            width: 100

          },
          {
            title: '交货日期',
            key: 'deliveryTime',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '产品ID',
            key: 'goodsId',
            type: JVXETypes.hidden,
            width: 100
          },
          {
            title: '产品物料ID',
            key: 'goodsMaterialId',
            type: JVXETypes.hidden,
            width: 100
          },
          {
            title: '产品编码',
            key: 'goodsCode',
            type: JVXETypes.hidden,
            width: 100
          },
          {
            title: '产品名称',
            key: 'goodsName',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '产品型号',
            key: 'goodsSpec',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '订单数量',
            key: 'orderNum',
            type: JVXETypes.normal,
            statistics: ['sum'],
            // validateRules: [
            //   {
            //     required: true,
            //     pattern: /^\d+(\.\d{1,2})?$/,
            //     message: '请输入${title}',
            //   },
            // ],
            width: 100
          },
          {
            title: '包材ID',
            key: 'packageId',
            type: JVXETypes.hidden,
            width: 100
          },
          {
            title: '包材物料ID',
            key: 'packageMaterialId',
            type: JVXETypes.hidden,
            width: 100
          },
          {
            title: '物料编码',
            key: 'packageCode',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '物料名称',
            key: 'packageName',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '规格型号',
            key: 'noneSpec',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '单位',
            key: 'meUnit_dictText',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '是否有版样',
            key: 'hasPattern',
            type: JVXETypes.hidden,
            width: 100
          },
          {
            title: '是否有版样',
            key: 'hasPattern_dictText',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '需求数量',
            key: 'requireNum',
            type: JVXETypes.normal,
            statistics: ['sum'],
            // validateRules: [
            //   {
            //     required: true,
            //     pattern: /^\d+(\.\d{1,2})?$/,
            //     message: '请输入${title}',
            //   },
            // ],
            width: 100
          },
          {
            title: '库存',
            key: 'wmsQuantity',
            type: JVXETypes.normal,
            width: 100
          },
          {
            title: '损耗率(%)',
            key: 'lossRate',
            type: JVXETypes.slot,
            slotName: 'lossRate',
            width: 100
          },
          {
            title: '采购数量',
            key: 'purchaseNum',
            type: JVXETypes.normal,
            statistics: ['sum'],
            // validateRules: [
            //   {
            //     required: true,
            //     pattern: /^\d+(\.\d{1,2})?$/, // 允许最多两位小数
            //     message: '请输入${title}',
            //   },
            // ],
            width: 100
          },
          {
            title: '价格',
            key: 'price',
            type: JVXETypes.inputNumber,
            width: 100
          },
          {
            title: '总价',
            key: 'totalPrice',
            type: JVXETypes.normal,
            statistics: ['sum'],
            width: 100
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.textarea,
            width: 100
          },
          {
            title: '包装要求',
            key: 'packageRemark',
            type: JVXETypes.textarea,
            width: 100
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '150px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/package/orderManage/add',
        edit: '/package/orderManage/edit',
        queryById: '/package/orderManage/queryById',
        packageOrderManageDetail: {
          list: '/package/orderManage/queryPackageOrderManageDetailByMainId',
        },
        listPackageMaterialItems: '/review/crmTradeOrder/listPackageMaterialItems',
      },
      unitDictOptions: {},
      zlunitDictOptions: {},
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {

    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.createOrgcode = user.departIds
    }

    this.initDictConfig()

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      //刷新子表数据
      this.editAfter()
    }
  },
  mounted() {},
  methods: {
    handlePreviewFile(props) {
      console.log(props.row, '版样文件')
      if (!props.row.files) {
        return this.$message.error("无版样文件,请到版样管理添加版样")
      }
      FilePreview(props.row.files)
    },
    onChange(record){
      if(record){
        console.log("Aaaaaaaaaaaaaaaaaaaaaaa=>",record)
        //采购数量：需求数量 * （1+损耗率%）-库存数量 -> 20250617: 向上取整
        record.row.purchaseNum=(((new Decimal(record.row.lossRate || 0).div(100).add(1)).times(new Decimal(record.row.proportion || 0).times(new Decimal(record.row.orderNum || 0))).sub(record.row.wmsQuantity)).ceil()).toString()
          /*lossRate: row.lossRate,*///说是损耗率不带出，要手填
          //总价：价格 * 采购数量
         record.row.totalPrice= (new Decimal(record.row.price || 0).times(((new Decimal(record.row.lossRate || 0).div(100).add(1)).times(new Decimal(record.row.proportion || 0).times(new Decimal(record.row.orderNum || 0)))))).toString()
         this.$forceUpdate();
        // 手动触发VxeTable的重新计算
        this.$nextTick(() => {
          const jvxeTable = this.$refs[this.refKeys[0]];
          if (jvxeTable) {
            // 访问内部的 VxeGrid 实例并调用 recalculate
            const vxeGrid = jvxeTable.$refs.vxe;
            if (vxeGrid) {
              const xTable = vxeGrid.$refs.xTable
              if (xTable) {
                xTable.handleTableData()
                xTable.updateFooter()
                xTable.updateCache()
                xTable.checkSelectionStatus()
                xTable.recalculate()
              }
            }
          }
        });
      }
    },
    getPfCode() {
      postAction('/sys/fillRule/executeRuleByCode/package_order_code', {}).then((res) => {
        this.model.code = res.result
      })
    },
    // async getZD(param) {
    //   // 获取数据字典数据
    //   const res = await getAction('/sys/api/queryEnableDictItemsByCode', { code: param })
    //   return res
    // },
    initDictConfig() {
      //初始化字典 - 主单位
      initDictOptions('ji_unit').then((res) => {
        let unitDictOptions = this.unitDictOptions
        if (res.success) {
          res.result.forEach(function (item, index) {
            unitDictOptions[item.value] = item.label
          })
        }
        this.unitDictOptions = unitDictOptions
      })
      //初始化字典 - 辅单位
      initDictOptions('zl_unit').then((res) => {
        let zlunitDictOptions = this.zlunitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            zlunitDictOptions[item.value] = item.label
          })
        }
        this.zlunitDictOptions = zlunitDictOptions
      })
    },
    // editClosedEvent({ row, column }) {
    //   let xTable = this.$refs.xTable
    //   let field = column.property
    //   let cellValue = row[field]
    //   if (row.procurementNum > row.planNum || row.procurementNum + row.generatedNum > row.planNum) {
    //     this.$refs.xTable.revertData(row)
    //     this.$XModal.message({ message: '数量有误，请检查', status: 'warning' })
    //   }
    //   // 判断单元格值是否被修改
    //   if (xTable.isUpdateByRow(row, field)) {
    //     //计算器
    //     // if(row.procurementNum && row.planNum){
    //     this.computeQuity(row).then((res) => {
    //       Object.keys(res.result).forEach((key) => {
    //         this.$set(row, key, res.result[key])
    //       })
    //       this.$refs.xTable.reloadRow(row, null, field)
    //       // this.loading = false
    //     })
    //     // }
    //   }
    // },
    addTemporary() {
      //临时新增
      if (this.model.packageOrderManageDetailList && this.model.packageOrderManageDetailList.length > 0 && this.model.packageOrderManageDetailList[0].planCode) {
        this.$XModal.message({ message: '临时不能与计划混加', status: 'warning' })
        return
      }
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    addPlan() {
      //追加选择采购计划
      this.$nextTick(() => {
        this.$refs.plan.add()
      })
    },
    selectSupplier() {
      //选择供应商
      this.$nextTick(() => {
        this.$refs.supplier.add()
      })
    },
    initSupplier(result) {
      if (this.supplier && this.supplier.id != result.id) {
        this.supplier = {}
        this.model.packageOrderManageDetailList = []
      }
      this.supplier = result
      this.model.supplierId = this.supplier.id
    },
    addBefore() {
      this.bussPackageProcurementDetailTable.dataSource = []
    },
    add(ids) {
      this.getPfCode()
      this.bussPackageProcurementDetailTable.dataSource = []
      console.log("order ids:"+ids)
      let packageMaterialItems = null
      if (ids != null) {
        getAction(this.url.listPackageMaterialItems, { ids: ids }).then((res) => {
          packageMaterialItems = res.result
          if (packageMaterialItems.length > 0) {
            packageMaterialItems.forEach((row, index) => {
              this.bussPackageProcurementDetailTable.dataSource.push({
                //订单ID
                orderId: row.orderId,
                schedulingNumber: row.schedulingNumber,
                arrived: row.arrived,
                deliveryTime: row.deliveryTime,
                //产品ID
                goodsId: row.goodsId,
                //产品物料ID
                goodsMaterialId: row.goodsMaterialId,
                goodsCode: row.goodsCode,
                goodsName: row.goodsName,
                goodsSpec: row.goodsSpec,
                //订单数量: 产品主数量
                orderNum: row.goodsMainQuantity,
                //包材ID
                packageId: row.packageId,
                //包材物料ID
                packageMaterialId: row.packageMaterialId,
                packageCode: row.packageCode,
                packageName: row.packageName,
                noneSpec: row.noneSpec,
                meUnit: row.meUnit,
                meUnit_dictText: row.meUnit_dictText,
                hasPattern: row.hasPattern,
                hasPattern_dictText: row.hasPattern_dictText,
                proportion: row.proportion,
                files: row.files,
                //需求数量：主数量 * 比例
                requireNum: (new Decimal(row.proportion || 0).times(new Decimal(row.goodsMainQuantity || 0))).toString(),
                //采购数量：需求数量 * （1+损耗率%） -> 20250617: 向上取整
               /* purchaseNum: (((new Decimal(row.lossRate || 0).div(100).add(1)).times(new Decimal(row.proportion || 0).times(new Decimal(row.goodsMainQuantity || 0)))).ceil()).toString(),*/
                /*lossRate: row.lossRate,*///说是损耗率不带出，要手填
                price: row.price,
                wmsQuantity: row.wmsQuantity,
                //总价：价格 * 采购数量
               /* totalPrice: (new Decimal(row.price || 0).times(((new Decimal(row.lossRate || 0).div(100).add(1)).times(new Decimal(row.proportion || 0).times(new Decimal(row.goodsMainQuantity || 0)))))).toString(),*/
                seq: index + 1,
              })
            })
          }
        })
      }
    },
    editClosedEvent({ row, column, cellValue }) {
      /*if (column.property === 'procurementNum' || column.property === 'procurementArrayPrice') {
        //如果输入数量或者价格时自动计算总价格
        if (
          this.bussPackageProcurementDetailTable.dataSource &&
          this.bussPackageProcurementDetailTable.dataSource.length > 0
        ) {
          let arr = this.bussPackageProcurementDetailTable.dataSource
          let price = 0
          let counts = 0
          arr.forEach((element) => {
            console.log(element.procurementNum)
            if (element.procurementNum) {
              counts += element.procurementNum
            }
            if (element.procurementNum && element.procurementArrayPrice) {
              price += element.procurementNum * element.procurementArrayPrice
            }
          })

          if (price > 0) {
            this.model.allPrice = price.toFixed(2)
          }

          if (arr[0].procurementArrayPrice && arr[0].procurementArrayPrice > 0) {
            this.model.arrivalPrice = arr[0].procurementArrayPrice
          }

          if (counts > 0) {
            this.model.num = counts
            this.$forceUpdate()
          }
        }
      }*/
      // 当修改"本次订单数量"或"价格"时触发计算
      if (['price'].includes(column.property)) {
        /*if (!row.purchaseNum || !row.price) {
          return
        }*/
        // 计算总价（保留两位小数）
        // row.totalPrice = (qty * price).toFixed(2)
        const totalPrice = (new Decimal(row.purchaseNum || 0).times(new Decimal(row.price || 0))).toString();

        // 使用Vue.set确保响应式更新
        this.$set(row, 'totalPrice', totalPrice);

        // 手动触发VxeTable的重新计算
        this.$nextTick(() => {
          const jvxeTable = this.$refs[this.refKeys[0]];
          if (jvxeTable) {
            // 访问内部的 VxeGrid 实例并调用 recalculate
            const vxeGrid = jvxeTable.$refs.vxe;
            if (vxeGrid) {
              const xTable = vxeGrid.$refs.xTable
              if (xTable) {
                xTable.handleTableData()
                xTable.updateFooter()
                xTable.updateCache()
                xTable.checkSelectionStatus()
                xTable.recalculate()
              }
            }
          }
        });
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter(record) {
      //如果没有明细先要复制一个空数组
      if (!record || record.packageOrderManageDetailList == null) {
        this.model.packageOrderManageDetailList = []
      }

      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.packageOrderManageDetail.list,
          params,
          this.bussPackageProcurementDetailTable
        )

        //刷新明细的时候 还要将这个数据传输到要提交的表单中
        if (this.bussPackageProcurementDetailTable) {
          this.model.packageOrderManageDetailList = this.bussPackageProcurementDetailTable.dataSource
        }
      }

      this.$nextTick(() => {})
    },
    requestSubTableData(url, params, table) {
      getAction(url, params).then(res => {
        if (res.success) {
          table.dataSource = res.result.map(item => ({
            ...item,
          }))
        }
      })
    },
    successBack(res) {
      let { result } = res
      this.model = result
      if (this.model.packageOrderManageDetailList && this.model.packageOrderManageDetailList.length > 0) {
        this.loadVendor()
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              validateError(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussMaterialProcurementDetailList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    submitForm() {
      const that = this
      // 触发表单验证
      // this.$refs.bussPackageMaterialProcurementDetail.validateTable().then((errMap) => {
      //   if (errMap) {
      //     this.$message.error('请检查表单明细内容')
      //     return
      //   } else {
      //
      //   }
      // })
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }

          if (this.bussPackageProcurementDetailTable && this.bussPackageProcurementDetailTable.dataSource) {
            this.model.packageOrderManageDetailList = this.bussPackageProcurementDetailTable.dataSource
            this.model.packageOrderManageDetailList.forEach((element) => {
              element.id = null
            })
          }

          // if (!this.model.packageOrderManageDetailList || this.model.packageOrderManageDetailList.length <= 0) {
          //   this.$message.warning('无包材明细不能保存！')
          //   that.confirmLoading = false
          //   return
          // }
          console.log(this.model)
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                //241119修改提交时还要判断是否直接进入审批流
                /*if (!this.model.id) {
                  this.model.dataId = res.message
                  that.applySubmit(this.model)
                }*/
                that.$message.success('保存成功')
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点

      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          let params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          //this.queryParams.createTime = parseTime(new Date())
          definitionStartByDataId(record.dataId, 'materialProcurementService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)

                // todoListNew(this.queryParams).then((response) => {
                //   if (response.success) {
                //     let result = response.result
                //     if (result) {
                //       let records = result.records
                //       if (records) {
                //         if (records[0]) {
                //           this.$message.info('即将跳转到单据审批界面！')
                //           this.$router.push({
                //             path: '/flowable/task/record/index',
                //             query: {
                //               procInsId: records[0].procInsId,
                //               deployId: records[0].deployId,
                //               taskId: records[0].taskId,
                //               businessKey: records[0].businessKey,
                //               nodeType: records[0].nodeType,
                //               category: records[0].category,
                //               finished: true,
                //             },
                //           })
                //         }
                //       }
                //     }
                //   } else {
                //   }
                // })
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      this.bussPackageProcurementDetailTable.dataSource.splice(
        this.bussPackageProcurementDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
        1
      )
    },
    handleOk() {
      //空方法 防止多次提交
    },
    popupCallback(value,row){
      this.model = Object.assign(this.model, row);
    },
  },
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 4px;
  margin-left: 4px;
}
</style>
